﻿using System.Diagnostics;

namespace XYAC.Framework.MonitorTireMaterialManual
{
    public sealed class ProcessSingleInstance
    {
        private static Mutex _mutex;
        public const string MutexName = "Global\\WohuaMesExtendAppMutex";
        public const string EventName = "Global\\WohuaMesExtendAppEvent";

        /// <summary>
        /// 通过互斥体以及信号接收事件创建窗体
        /// </summary>
        /// <returns></returns>
        public static bool AlreadyRunning2()
        {
            // 尝试创建互斥体
            _mutex = new Mutex(true, MutexName, out bool createdNew);

            if (createdNew)
            {
                // 第一次运行时创建命名事件
                EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, EventName);
            }
            else
            {
                // 如果已经有实例在运行，则触发事件
                EventWaitHandle.OpenExisting(EventName).Set();
                return true;
            }

            return false;
        }

        public static void ReleaseMutex()
        {
            _mutex?.ReleaseMutex();
        }

        /// <summary>
        /// 通过Windows api激活窗体
        /// </summary>
        /// <returns></returns>
        public static bool AlreadyRunning()
        {
            bool running = false;
            try
            {
                // Getting collection of process  
                Process currentProcess = Process.GetCurrentProcess();
                // Check with other process already running   
                foreach (var p in Process.GetProcesses())
                {
                    if (p.Id != currentProcess.Id) // Check running process   
                    {
                        if (p.ProcessName.Equals(currentProcess.ProcessName) == true)
                        {
                            running = true;

                            IntPtr hFound = p.MainWindowHandle;
                            if (User32API.IsIconic(hFound)) // If application is in ICONIC mode then  
                                User32API.ShowWindow(hFound, User32API.SW_RESTORE);
                            User32API.SetForegroundWindow(hFound); // Activate the window, if process is already running  


                            break;
                        }
                    }
                }
            }
            catch { }
            return running;
        }
    }

}
